<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use app\common\model\ActivityCategory;
use app\common\model\CategoryType as TypeModel;

class CategoryType extends Controller
{
    protected $middleware = ['adminauth'];
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index($category_id)
    {
        $category = ActivityCategory::getOrFail($category_id);
        if(request()->isAjax())
        {
            return json($category->type);
        }
        return view('category_type/index', ['category' => $category]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create($category_id)
    {
        $category = ActivityCategory::get($category_id);
        return view('category_type/create', ['category' => $category]);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request, $category_id)
    {
        $result = $this->validate($request->post(),'app\admin\validate\catetype');
        if($result !== true)
        {
            $this->error($result);
        }
        $category = ActivityCategory::getOrFail($category_id);
        $category->type()->save($request->post());
        $this->redirect('category_type/index', ['category_id' => $category_id]);
        //$this->success('添加成功', 'admin/category_type/index/category_id/'.$category_id);
        //dump($request->post());
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id, $category_id)
    {
        $category = ActivityCategory::getOrFail($category_id);
        $data = $category->type()->getOrFail($id);
        return view('category_type/create', [
            'data' => $data,
            'category' => $category,
        ]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $category_id, $id)
    {
        $category = ActivityCategory::getOrFail($category_id);
        $type = $category->type()->getOrFail($id);
        $type->save($request->post());
        $this->redirect('category_type/index', ['category_id' => $category_id]);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        TypeModel::destroy($id);
        return json(['status' => true]);
    }
}
